package com.hsnn.medstgmini.pro.project.dao.impl;

import java.sql.Blob;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.LobHelper;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.pro.project.dao.ContractModelDao;
import com.hsnn.medstgmini.pro.project.model.ContractModel;
import com.hsnn.medstgmini.pro.project.model.ContractModelLog;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.Pagination;

@Repository
public class ContractModelDaoImpl implements ContractModelDao{
	
	@Autowired
	private HibernateSqlUtil hibernateUtil;
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	/**
	 * @category 获取合同模板列表页
	 * @author zhouqi
	 * @date 2015年9月8日10:08:08
	 * @return Pagination
	 */
	public Pagination getContractModelListPage(Pagination page){
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT A.contract_model_id AS contractModelId, A.contract_model_code AS contractModelCode,");
		sql.append(" A.contract_model_name AS contractModelName, A.`status` AS status, A.version as version");
		sql.append(" FROM contract_model A where 1=1");
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank((page.getConditions().get("contractModelName")))){
			sql.append(" AND A.contract_model_name like :contractModelName");
			params.put("contractModelName","%"+page.getConditions().get("contractModelName")+"%");
		}
		if(StringUtils.isNotBlank((page.getConditions().get("status")))){
			sql.append(" AND A.`status` = :status");
			params.put("status", page.getConditions().get("status"));
		}
		if(StringUtils.isNotBlank((page.getConditions().get("contractModelCode")))){
			sql.append(" AND A.contract_model_code = :contractModelCode");
			params.put("contractModelCode", page.getConditions().get("contractModelCode"));
		}
		return hibernateUtil.getSqlPageMapList(sql.toString(), params, page);
	}
	
	/**
	 * @category 通过id获取合同模板
	 * @author zhouqi
	 * @date 2015年9月8日10:08:08
	 * @param id
	 * @return Pagination
	 */
	public ContractModel getContractModelById(String id){
		Session session = sessionFactory.getCurrentSession();
		ContractModel contractModel = (ContractModel) session.get(ContractModel.class, id);
		session.clear();
		return contractModel;
	}
	
	/**
	 * @category 保存或修改合同模板
	 * @author zhouqi
	 * @date 2015年9月8日10:08:08
	 * @param type 操作类型，修改或添加
	 * @param contractModel
	 * @return Boolean
	 */
	public Boolean saveOrUpdateContractModel(Integer type, ContractModel contractModel){
		Session session = sessionFactory.getCurrentSession();
		LobHelper lobHelper = session.getLobHelper();
		try{
			Blob blob = lobHelper.createBlob(contractModel.getContent().getBytes("utf-8"));
			contractModel.setBlobContent(blob);
			if(type == Constants.OP_TYPE_EDIT){
				session.update(contractModel);
			}
			if(type== Constants.OP_TYPE_ADD){
				session.save(contractModel);
			}
			session.flush();
			session.clear();
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * @category 获取合同模板页日志列表
	 * @author zhouqi
	 * @date 2015年9月8日10:08:08
	 * @return Pagination
	 */
	public Pagination getContractModelLogListPage(Pagination page){
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT A.log_id as logId, A.contract_model_id AS contractModelId, A.contract_model_code AS contractModelCode,");
		sql.append(" A.contract_model_name AS contractModelName, A.`status` AS status,date_format(A.upd_datetime,'%Y-%m-%d %H:%i:%S') as updDateTime, B.`name` as updUser,");
		sql.append(" A.version as version FROM contract_model_log A ");
		sql.append(" left join sys_user B on A.upd_user = B.id");
		sql.append(" where 1=1");
		Map<String,Object> params = new HashMap<String, Object>();
		if(StringUtils.isNotBlank((page.getConditions().get("contractModelName")))){
			sql.append(" AND A.contract_model_name like :contractModelName");
			params.put("contractModelName", page.getConditions().get("contractModelName"));
		}
		if(StringUtils.isNotBlank((page.getConditions().get("status")))){
			sql.append(" AND A.`status` = :status");
			params.put("status", page.getConditions().get("status"));
		}
		if(StringUtils.isNotBlank((page.getConditions().get("contractModelId")))){
			sql.append(" AND A.contract_model_id = :contractModelId");
			params.put("contractModelId", page.getConditions().get("contractModelId"));
		}
		if(StringUtils.isNotBlank((page.getConditions().get("startPoint")))){
			sql.append(" AND A.upd_datetime > :startPoint");
			String startPoint = page.getConditions().get("startPoint");
			params.put("startPoint", DateUtil.StringTime2Timestamp(startPoint));
		}
		if(StringUtils.isNotBlank((page.getConditions().get("endPoint")))){
			sql.append(" AND A.upd_datetime <:endPoint");
			String endPoint = page.getConditions().get("endPoint");
			params.put("endPoint", DateUtil.StringTime2Timestamp(endPoint));
		}
		sql.append(" order by A.upd_datetime DESC");
		return hibernateUtil.getSqlPageMapList(sql.toString(), params, page);
	}
	
	/**
	 * @category 保存或修改合同模板
	 * @author zhouqi
	 * @date 2015年9月8日10:08:08
	 * @param contractModelLog
	 * @param type 操作类型，修改或添加
	 * @return Boolean
	 */
	public Boolean saveOrUpdateContractModelLog(Integer type, ContractModelLog contractModelLog){
		Session session = sessionFactory.getCurrentSession();
		LobHelper lobHelper = session.getLobHelper();
		String stringContent = contractModelLog.getContent();
		try{
			Blob blobContent = lobHelper.createBlob(stringContent.getBytes("utf-8"));
			contractModelLog.setBlobContent(blobContent);
			if(type == Constants.OP_TYPE_EDIT){
				session.update(contractModelLog);
			}
			if(type == Constants.OP_TYPE_ADD){
				session.save(contractModelLog);
			}
			session.flush();
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 * @category 获取修改前后对比
	 * @author zhouqi
	 * @date 2015年9月9日08:49:26
	 * @param contractModelId
	 * @param updDateTime
	 * @return List<ContractModelLog>
	 */
	@Override
	public List<ContractModelLog> getCompareContactModelLogList(String contractModelId, String updDateTime){
		Session session = sessionFactory.getCurrentSession();
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT A.* FROM contract_model_log A where 1=1");
		if(StringUtils.isNotBlank(updDateTime)){
			sql.append(" AND A.upd_datetime <= :updDateTime");
		}
		if(StringUtils.isNotBlank(contractModelId)){
			sql.append(" AND A.contract_model_id = :contractModelId");
		}
		sql.append(" order by A.upd_datetime DESC limit 2");
		Query query = session.createSQLQuery(sql.toString()).addEntity(ContractModelLog.class);
		if(StringUtils.isNotBlank(updDateTime)){
			query.setParameter("updDateTime", DateUtil.StringTime2Timestamp(updDateTime));
		}
		if(StringUtils.isNotBlank(contractModelId)){
			query.setParameter("contractModelId",contractModelId);
		}
		return query.list();
	}
}
